'use strict';
/**
 * Created by FreezeSoul on 2015/10/24.
 */
define([
    "app/core/base",
    "app/core/util",
    "../commonMeta",
    "jquery",
    "underscore",
    'JSONParse',
    'loglevel',
    'jqueryTmpl'
], function (Chart, Util, Meta, $, _, JSON, log) {

    var property = {
        config: "property",
        option: [
            {
                group: '基础',
                id: 'title',
                name: '主标题',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'title',
                tooltip: '主标题'
            },
            {
                group: '基础',
                id: 'value',
                name: '值对象',
                enable: false,
                type: 'number',
                value: 0,
                default: 0,
                link: 'value',
                tooltip: '值对象初始值'
            },
            {
                group: '基础',
                id: 'subTitle',
                name: '子标题',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'subTitle',
                tooltip: '子标题'
            },
            {
                group: '基础',
                id: 'icon',
                name: '图标',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'icon',
                tooltip: '图标，支持Bootstrap 3.X及Font-Awesome 4.5的Icon Class<br/>地址：1.http://getbootstrap.com/components/<br/>2.https://fortawesome.github.io/Font-Awesome/icons/'
            },
            {
                group: '基础',
                id: 'theme',
                name: '主题样式',
                enable: false,
                type: 'select',
                value: 'none',
                default: 'none',
                data: [
                    {value: 'none', text: 'None'},
                    {value: 'danger', text: 'danger'},
                    {value: 'warning', text: 'warning'},
                    {value: 'primary', text: 'primary'},
                    {value: 'success', text: 'success'},
                    {value: 'info', text: 'info'}
                ],
                link: 'theme',
                tooltip: '主题样式'
            },
            {
                group: '绑定',
                id: 'binding',
                name: '绑定值对象',
                enable: false,
                type: 'textBinding',
                dataset: '',
                ctype: 'all',
                column: {},
                tooltip: '值对象绑定'
            }, {
                group: '绑定',
                id: 'FilterName',
                name: '过滤列名称',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterName',
                tooltip: '绑定数据集，客户端过滤字段列名称'
            },
            {
                group: '绑定',
                id: 'FilterValue',
                name: '过滤列默认值',
                enable: false,
                type: 'text',
                value: '',
                default: '',
                link: 'filterValue',
                tooltip: '绑定数据集，客户端过滤字段默认值'
            },
            {
                group: '事件',
                id: 'LabelClick',
                name: '点击跳转事件',
                enable: true,
                type: 'pivotEvent',
                value: {
                    Event: "LabelClick",
                    Params: [
                        {Value: "Value", Name: "数值"},
                        {Value: "Title", Name: "标题"},
                        {Value: "SubTitle", Name: "副标题"}
                    ]
                },
                tooltip: '点击跳转事件，钻取设置'
            }
        ].concat($.extend(true, [], Meta.commonProperties)),
        MapOption: function (option) {
            Util.linkOption(this.option, option);
        }
    };

    var label = Chart.extend({
        constructor: function (layout) {
            this._layout = layout;
            this._label = null;
            this._lastdata = null;
            this._container = null;
            this._template = '<div class="label-container" style="${css_container}">' +
                '  <div style="${css_info_box}${css_theme}">' +
                '<div style="float:left;width: 100px;height: 100%;">' +
                '    <i class="${icon}" style="${css_i_icon}"></i>' +
                '</div>' +
                '<div style="margin: 10px 20px;height: 100%;width: 100%;position: absolute;padding-left: 100px;">' +
                '    <div class="label-count" style="${css_count}">${value}</div>' +
                '    <div class="label-title" style="${css_title}">${title}</div>' +
                '    <div class="label-desc" style="${css_desc}">${subTitle}</div>' +
                '</div>' +
                '  </div>' +
                '</div>';

            this._css_container = "" +
                "height: 100%;" +
                "width: 100%;" +
                "cursor: pointer;";

            this._css_info_box = "" +
                "height: 100%;" +
                "width: 100%;" +
                //"border: 1px solid black;" +
                "margin: 0;" +
                "padding: 20px;" +
                "-webkit-box-shadow: inset 0 0 1px 1px rgba(255, 255, 255, 0.35), 0 3px 1px -1px rgba(0, 0, 0, 0.1);" +
                "-moz-box-shadow: inset 0 0 1px 1px rgba(255, 255, 255, 0.35), 0 3px 1px -1px rgba(0, 0, 0, 0.1);" +
                "box-shadow: inset 0 0 1px 1px rgba(255, 255, 255, 0.35), 0 3px 1px -1px rgba(0, 0, 0, 0.1);";

            this._css_i_icon = "" +
                "display: block; " +
                "opacity: 0.75; " +
                "height: 100%; " +
                "font-size: 60px; " +
                "line-height: 100px; " +
                "width: 100px; " +
                "float: left; " +
                "text-align: center;" +
                "margin-right: 20px; " +
                "padding-right: 20px; ";

            this._css_count = "" +
                "margin-top: -10px;" +
                "font-size: 34px; " +
                "font-weight: 700;";

            this._css_count = "" +
                "margin-top: -10px;" +
                "font-size: 34px; " +
                "font-weight: 700;";

            this._css_title = "" +
                "font-size: 16px; " +
                "text-transform: uppercase; " +
                "font-weight: 600;";

            this._css_desc = "" +
                "margin-top: 10px;" +
                "font-size: 14px;" +
                "padding-right: 60px;";


            this._theme = [
                {
                    name: "none",
                    css: "background: transparent;color: black;",
                    borderCss: "border-right: 2px solid rgba(0, 0, 0, 0.5); "
                },
                {
                    name: "danger",
                    css: "background: #ff5454; border: 1px solid #ff2121;color: white;",
                    borderCss: "border-right: 2px solid rgba(255, 255, 255, 0.5); "
                },
                {
                    name: "warning",
                    css: "background: #fabb3d; border: 1px solid #f9aa0b;color: white;",
                    borderCss: "border-right: 2px solid rgba(255, 255, 255, 0.5); "
                },
                {
                    name: "primary",
                    css: "background: #20a8d8; border: 1px solid #1985ac;color: white;",
                    borderCss: "border-right: 2px solid rgba(255, 255, 255, 0.5); "
                },
                {
                    name: "info",
                    css: "background: #67c2ef; border: 1px solid #39afea;color: white;",
                    borderCss: "border-right: 2px solid rgba(255, 255, 255, 0.5); "
                },
                {
                    name: "success",
                    css: "background: #79c447; border: 1px solid #61a434;color: white;",
                    borderCss: "border-right: 2px solid rgba(255, 255, 255, 0.5); "
                }
            ];

            this._option = {
                Series: [],
                Events: [],
                Extend: $.extend(true, {}, property),
                Option: {
                    uuid: '',
                    class: '',
                    display: true,
                    theme: 'success',
                    icon: 'fa fa-smile-o',
                    value: '0',
                    title: '主标题',
                    subTitle: '子标题',
                    initScript: '',
                    disposeScript: ''
                }
            };
        },
        init: function (element) {
            try {
                this._container = element;
            } catch (e) {
                log.error(e);
            }
        },
        _readProperty: function () {
            try {
                if (!this._option.Extend) return;
                Util.deepMapOption(property, this._option.Extend, this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        _render: function (option) {
            var optionCopy = $.extend(true, {}, option);
            var themeCss = _.findWhere(this._theme, {name: option.theme});
            optionCopy.css_theme = themeCss ? themeCss.css : "";
            optionCopy.css_container = this._css_container;
            optionCopy.css_info_box = this._css_info_box;
            optionCopy.css_i_icon = this._css_i_icon + (themeCss ? themeCss.borderCss : "");
            optionCopy.css_count = this._css_count;
            optionCopy.css_title = this._css_title;
            optionCopy.css_desc = this._css_desc;
            var $element = $.tmpl(this._template, optionCopy);
            $(this._container).empty();
            $element.appendTo(this._container);
            this._bindEvent($element);

            //Util.setCommonMeta(this, this._container, this._option.Option);
            //Util.initChartLifeTime(this, this._container, this._option.Option);

            return $element;
        },
        _bindEvent: function (element) {
            var _this = this;
            $(element).on("click", function (e) {
                if (_this._layout
                    && _this._layout.navigate
                    && _this._option.Events
                    && _this._option.Events.length > 0) {

                    var registerEvent = _.findWhere(_this._option.Events, {Event: "LabelClick"});
                    if (registerEvent) {
                        var pageId = registerEvent.PageId;
                        var params = registerEvent.Params;
                        var args = [];
                        var dParam = _.findWhere(params, {Value: "Value"});
                        if (dParam && dParam.ParamName) {
                            args.push({
                                ParamName: dParam.ParamName,
                                ParamValue: $(element).find(".label-count").text()
                            });
                        }
                        var mParam = _.findWhere(params, {Value: "Title"});
                        if (mParam && mParam.ParamName) {
                            args.push({
                                ParamName: mParam.ParamName,
                                ParamValue: $(element).find(".label-title").text()
                            });
                        }
                        var sParam = _.findWhere(params, {Value: "SubTitle"});
                        if (sParam && sParam.ParamName) {
                            args.push({
                                ParamName: sParam.ParamName,
                                ParamValue: $(element).find(".label-desc").text()
                            });
                        }
                        _this._layout.navigate(pageId, args);
                    }
                    e.preventDefault();
                }
            });

            if (!this._filterDataHandle) {
                this._filterDataHandle = function (params) {
                    _this.filterDataHandle.call(_this, params);
                };
            }
            this._layout.removeListener("filterData", this._filterDataHandle);
            this._layout.addListener("filterData", this._filterDataHandle);
        },
        filterDataHandle: function (params) {
            var _this = this;
            var flag = false;
            var filterColumn = _.findWhere(this._option.Extend.option, {name: '过滤列名称'});
            var filterValue = _.findWhere(this._option.Extend.option, {name: '过滤列默认值'});

            if (filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                for (var prop in params) {
                    if (!params.hasOwnProperty(prop)) continue;
                    if (filterColumn.value === prop) {
                        filterValue.value = params[prop];
                        flag = true;
                    }
                }
            }
            if (flag && _this._lastdata) {
                _this.setData(_this._lastdata);
            }
        },
        example: function () {
            try {

                var exampleOption = {
                    theme: 'success',
                    icon: 'fa fa-smile-o',
                    value: '570,000,000',
                    title: '微信登录用户',
                    subTitle: '微信 9 月平均日登录用户达到 5.7 亿，这个数据略惊人。'
                };

                this._label = this._render(exampleOption);
            } catch (e) {
                log.error(e);
            }
        },
        _filterTable: function (option, table) {
            var filterColumn = _.findWhere(option, {name: '过滤列名称'});
            var filterValue = _.findWhere(option, {name: '过滤列默认值'});

            if (table && filterColumn && filterValue
                && filterColumn.enable && filterValue.enable
                && filterColumn.value !== "" && filterValue.value !== ""
            ) {
                var tableCopy = _.map(table, _.clone);
                return _.filter(tableCopy, function (row) {
                    return row[filterColumn.value] === filterValue.value;
                });
            }
            return table;
        },
        _bindData: function (data) {
            var bindProperty = _.findWhere(this._option.Extend.option, {type: 'textBinding'});
            if (!bindProperty || !bindProperty.dataset) return;
            var dataSetCode = bindProperty.dataset;
            var table = data[dataSetCode];
            table = this._filterTable(this._option.Extend.option, table);
            if (table && table.length > 0 && bindProperty.column) {
                var row = table[0];
                var columnName = bindProperty.column.ColumnName;
                if (columnName) {
                    this._option.Option.value = row[columnName];
                }
            }
        },
        setData: function (data) {
            try {
                this._lastdata = data;

                this._readProperty();

                if (data
                    && this._option.Binding
                    && this._option.Binding.length > 0
                    && this._option.Extend
                ) {
                    this._bindData(data);
                }
                this._label = this._render(this._option.Option);
            } catch (e) {
                log.error(e);
            }
        },
        setOption: function (option) {
            try {
                return this._option = $.extend(true, {}, option);
            } catch (e) {
                log.error(e);
            }
        },
        getOption: function () {
            try {
                this._readProperty();
            } catch (e) {
                log.error(e);
            }
            return this._option;
        },
        setTheme: function (theme) {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        resize: function () {
            try {
            } catch (e) {
                log.error(e);
            }
        },
        showLoading: function () {
            try {
                if (this._layout && this._layout.showLoading) {
                    this._layout.showLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        hideLoading: function () {
            try {
                if (this._layout && this._layout.hideLoading) {
                    this._layout.hideLoading(this);
                }
            } catch (e) {
                log.error(e);
            }
        },
        dispose: function () {
            try {
                $(this._label).off().remove();
                this._layout.removeListener("filterData", this._filterDataHandle);
                //Util.disposeChartLifeTime(this, this._container, this._option.Option);

            } catch (e) {
                log.error(e);
            }
        },
        getElement: function () {
            return this._element;
        },
        getChart: function () {
            return this._label;
        }
    });

    return {
        Chart: label,
        Property: property
    };
});